package com.sf.guava.collect;

import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import java.util.Iterator;
import java.util.Set;

/**
 * @Classname MultisetTest
 * @Description 处理重复元素
 * @Date 2019/12/11 0011 17:13
 * @Created by 埔枘
 */
public class MultisetTest {

    public static void main(String[] args) {
        Multiset<String> multiset = getMultiset();
        printBCount(multiset);
        //打印 元素 总数
        System.out.println("Total Size : "+multiset.size());
        //去重复
        Set<String> set = multiset.elementSet();
        //display the elements of the set
        System.out.println("Set [");
        for (String s : set) {
            System.out.println(s);
        }
        System.out.println("]");

        //迭代打印所有元素
        Iterator<String> iterator  = multiset.iterator();
        System.out.println("MultiSet [");
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
        System.out.println("]");

        //打印不同元素 出现的次数
        System.out.println("MultiSet [");
        for (Multiset.Entry<String> entry : multiset.entrySet())
        {
            System.out.println("Element: "+entry.getElement() +", Occurrence(s): " + entry.getCount());
        }
        System.out.println("]");

        //删除 指定 个数的元素
        multiset.remove("b",2);
        //print the occurrence of an element
        System.out.println("Occurence of 'b' : "+multiset.count("b"));


    }

    private static void printBCount(Multiset<String> multiset) {
        //打印 B 出现的次数
        System.out.println("Occurrence of 'b' : "+multiset.count("b"));
    }

    private static Multiset<String> getMultiset() {
        //创建 重复元素的集合
        Multiset<String> multiset = HashMultiset.create();
        multiset.add("a");
        multiset.add("b");
        multiset.add("c");
        multiset.add("d");
        multiset.add("a");
        multiset.add("b");
        multiset.add("c");
        multiset.add("b");
        multiset.add("b");
        multiset.add("b");
        return multiset;
    }
}
